package cc.abanlee.framework.apilog.core.filter;

import cc.abanlee.framework.apilog.core.service.ApiAccessLogFrameworkService;
import cc.abanlee.framework.apilog.core.vo.ApiAccessLog;
import cc.abanlee.framework.common.pojo.CommonResult;
import cc.abanlee.framework.web.core.util.WebFrameworkUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: create by 飞鱼
 * @version: v1.0
 * @description:
 * @date:2022/8/16
 */
@Slf4j
public class ApiAccessLogFilter extends OncePerRequestFilter {

    private ApiAccessLogFrameworkService apiAccessLogFrameworkService;

    public ApiAccessLogFilter(ApiAccessLogFrameworkService apiAccessLogFrameworkService) {
        this.apiAccessLogFrameworkService = apiAccessLogFrameworkService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 继续过滤器
        filterChain.doFilter(request, response);

        this.createApiAccessLog(request);
    }

    private void createApiAccessLog(HttpServletRequest request){
        ApiAccessLog accessLog = new ApiAccessLog();
        this.buildApiAccessLogDTO(accessLog,request);
        apiAccessLogFrameworkService.createApiAccessLog(accessLog);
    }
    private void buildApiAccessLogDTO(ApiAccessLog accessLog,HttpServletRequest request){

        CommonResult<?> commonResult = WebFrameworkUtils.getCommonResult(request);
        if(commonResult!=null){
            accessLog.setResultCode(commonResult.getCode());
            accessLog.setResultMsg(commonResult.getMsg());
        }else {
            accessLog.setResultCode(0);
            accessLog.setResultMsg("");
        }
        accessLog.setRequestUrl(request.getRequestURI());
        accessLog.setRequestMethod(request.getMethod());
    }
}
